<template>
  <div class="device-details">
    <div class="offline mask" v-show="!device.online" transition="fromTop">
      <div class="offline-tips">
        <span>设备已离线！</span>
      </div>
    </div>
    <div class="menu-btn-box" @touchend.stop="showMenuModal=true">
      <div class="menu-btn">
        <span class="menu-icon-box">
          <menu-btn @tap="showMenuModal=true"></menu-btn>
        </span>
        <span class="text">更多</span>
      </div>
    </div>
    <div class="mask" v-show="showMenuModal" @touchend.self="showMenuModal=false" transition="opacity">
      <div class="modal-box" v-show="showMenuModal" transition="fromRightTop">
        <div class="li" @touchend="onRenameBtn">
          <span>重命名</span>
        </div>
        <div class="li" @touchend="onDeleteBtn">
          <span>删除设备</span>
        </div>
        <div class="li">
          <span>温度告警规则</span>
          <select v-if="showMenuModal" class="select select-temperature" v-model="alert.temperature" @change="temperatureAlertChange">
            <option v-for="temperature in option.temperature" :value="temperature.value">{{temperature.text}}</option>
          </select>
        </div>
        <div class="li">
          <span>有害气体告警规则</span>
          <select v-if="showMenuModal" class="select select-gas" v-model="alert.gas" @change="gasAlertChange">
            <option v-for="gas in option.gas" :value="gas.value">{{gas.text}}</option>
          </select>
        </div>
      </div>
    </div>
    <div class="device-state-box">
      <div class="warn-box" v-show="haswarn">
        <div class="warn smoke-box" :class="{'visible': warnType.smoke}">
          <div class="icon-box icon-smoke">
            <!-- <i class="icon-smoke"></i> -->
          </div>
          <div class="text">
            <span>烟雾告警</span>
          </div>
        </div>
        <div class="warn fire-box" :class="{'visible': warnType.fire}">
          <div class="icon-box icon-fire">
            <!-- <i class="icon-fire"></i> -->
          </div>
          <div class="text">
            <span>火灾告警</span>
          </div>
        </div>
        <div class="warn gas-box" :class="{'visible': warnType.gas}">
          <div class="icon-box icon-gas">
            <!-- <i class="icon-gas"></i> -->
          </div>
          <div class="text">
            <span>有害气体告警</span>
          </div>
        </div>
      </div>
      <div class="this-state" :class="{'normal': !haswarn}">
        <div class="icon-box" :class="{'light-red': haswarn, 'light-green': !haswarn}"></div>
        <span>{{warnText}}</span>
      </div>
    </div>
    <div class="device-info">
      <div class="container">
        <div class="info smoke-box">
          <div class="title">
            <span>烟雾</span>
          </div>
          <div class="msg">
            <span v-show="device.online">{{device.smoke?'有':'无'}}</span>
            <span v-else>--</span>
          </div>
        </div>
        <div class="info temperature-box">
          <div class="title">
            <span>温度</span>
          </div>
          <div class="msg">
            <span v-show="device.online && device.temperature!==null">{{device.temperature ||　0}}<i>℃</i></span>
            <span v-else>--</span>
          </div>
        </div>
        <div class="info gas-box">
          <div class="title">
            <span>有害气体</span>
          </div>
          <div class="msg">
            <span v-show="device.online && device.gas!==null">{{device.gas || '无'}}</span>
            <span v-else>--</span>
          </div>
        </div>
      </div>
    </div>

    <modal :show="showRenameModal" @close="showRenameModal=false">
      <div slot="body">
        <div class="rename-box">
          <div class="input-box" v-if="showRenameModal">
            <input type="text" class="rename-input" v-model="newName">
          </div>
          <div class="clear-btn icon_delete_gray" @touchend="newName=''"></div>
        </div>
      </div>
      <div slot="footer" class="btn-group">
        <div class="btn-box" @touchend="showRenameModal=false">
          <span class="btn">取消</span>
        </div>
        <div class="btn-box" @touchend="setNewName">
          <span class="btn">确定</span>
        </div>
      </div>
    </modal>
    <modal :show="showDeleteModal" @close="showDeleteModal=false">
      <div slot="body">
        <p>您是否确定删除该设备？</p>
      </div>
      <div slot="footer" class="btn-group">
        <div class="btn-box" @touchend="showDeleteModal=false">
          <span class="btn">取消</span>
        </div>
        <div class="btn-box" @touchend="deleteDevice">
          <span class="btn">确定</span>
        </div>
      </div>
    </modal>
    <iframe v-if="showIframe" src="./static/logo.png" style="display:none"></iframe>
  </div>
</template>

<script>
  var MenuModal = require('../../../shared/components/menu-modal.vue')
  var MenuBtn = require('../../../shared/components/menu-btn.vue')
  var Range = require('../../../shared/components/range.vue')
  var Modal = require('../../../shared/components/modal.vue')
  var base64 = require('base-64')
  import { setDeviceInfo } from '../../api/index.js'
  // import SDK from '../../helpers/sdk'
  // import api from '../../api'
  import { globalMixins } from '../../mixins'

  export default {
    mixins: [globalMixins],

    components: {
      'modal': Modal,
      'menu-modal': MenuModal,
      'menu-btn': MenuBtn,
      'v-range': Range
    },

    data () {
      return {
        // 显示菜单浮层标志位
        showMenuModal: false,
        // 显示删除浮层标志位
        showDeleteModal: false,
        // 显示重命名浮层标志位
        showRenameModal: false,
        // 当前设备名称
        deviceName: '',
        // 存放新的设备名称
        newName: '',
        // 当前设备id
        deviceId: '',
        // 当前设备信息
        device: {
          online: 1,
          type: 'office-room',
          smoke: false,
          temperature: null,
          gas: null,
          connect: null
        },
        // 存放当前告警规则
        alert: {
          temperature: 30,
          gas: 50
        }
      }
    },
    computed: {
      warnType () {
        var result = {
          smoke: Boolean(this.device.smoke),
          fire: this.device.temperature - 0 >= this.alert.temperature - 0,
          gas: this.device.gas - 0 >= this.alert.gas - 0
        }
        return result
      },
      /**
       * 下拉框选项
       * @return {[type]} [description]
       */
      option () {
        var result = {
          temperature: [],
          gas: []
        }
        for (let i = 3; i <= 10; i++) {
          result.temperature[i - 3] = {
            value: i * 10,
            text: i + '0℃'
          }
        }
        for (let i = 1; i <= 20; i++) {
          result.gas[i - 1] = {
            value: i * 5,
            text: i * 5 + '%'
          }
        }
        return result
      },
      /**
       * 告警个数
       * @return {[type]} [description]
       */
      warnCount () {
        var count = 0
        for (var key in this.warnType) {
          if (this.warnType.hasOwnProperty(key)) {
            if (this.warnType[key]) {
              count++
            }
          }
        }
        return count
      },
      /**
       * 是否有告警
       * @return {[type]} [description]
       */
      haswarn () {
        return Boolean(this.warnCount)
      },
      /**
       * 告警提示文字
       * @return {[type]} [description]
       */
      warnText () {
        var result = '状态正常'
        if (this.warnCount === 1) {
          if (this.warnType.smoke) {
            result = '烟雾告警异常'
          } else if (this.warnType.fire) {
            result = '火灾告警异常'
          } else if (this.warnType.gas) {
            result = '有害气体告警异常'
          }
        } else if (this.warnCount > 1) {
          result = '危险！请尽快疏散'
        }
        return result
      }
    },
    route: {
      data () {
        this.deviceId = this.$route.params.deviceId
        console.log(this.deviceId)
        // this.setTitle(this.deviceName)
        this.deviceName = document.title
      }
    },
    ready () {
      this.deviceInit(window.devices)
      // this.hideLoading()
    },
    methods: {
      temperatureAlertChange () {
        this.showMenuModal = false
        if (this.device.connect) {
          console.log(this.alert.temperature)
          var data = '3' + this.alert.temperature.toString()
          var encodeDate = {
            data: base64.encode(data),
            type: 'datapoint'
          }

          this.device.connect.emit('senddata', encodeDate, (res) => {
            console.log(res)
            if (res.status === 200) {
              this.showMessage('设置告警温度为' + this.alert.temperature + '℃')
            }
          })
        } else {
          this.showMessage('无设备连接')
        }
      },
      gasAlertChange () {
        this.showMenuModal = false
        if (this.device.connect) {
          console.log(this.alert.gas)
          var data = '4' + this.alert.gas.toString()
          console.log(data)
          var encodeDate = {
            data: base64.encode(data),
            type: 'datapoint'
          }

          this.device.connect.emit('senddata', encodeDate, (res) => {
            console.log(res)
            if (res.status === 200) {
              this.showMessage('设置有害气体告警为' + this.alert.gas + '%')
            }
          })
        } else {
          this.showMessage('无设备连接')
        }
      },
      /**
       * 设置新的设备名字
       */
      setNewName () {
        var params = {
          device_name: this.newName
        }
        console.log(this.deviceId)
        this.log('设置新的设备' + this.deviceId + '的名字' + JSON.stringify(params))
        // index.js暴露的修改设备信息参数
        setDeviceInfo(this.deviceId, params).then((res) => {
          this.log('更新设备信息接口返回信息' + JSON.stringify(res))
          var name = this.newName
          this.deviceName = name
          this.device.connect.name = name
          this.setTitle(name)
          this.showRenameModal = false
          this.showMessage('重命名成功')
        }).catch((err) => {
          this.log('修改设备名称接口返回错误' + JSON.stringify(err))
          this.showMessage('重命名失败')
        })
      },
      /**
       * 重命名按钮按下
       * @return {[type]} [description]
       */
      onRenameBtn () {
        this.newName = this.deviceName
        this.showRenameModal = true
        this.showMenuModal = false
      },
      /**
       * 删除按钮按下
       * @return {[type]} [description]
       */
      onDeleteBtn () {
        this.showDeleteModal = true
        this.showMenuModal = false
      },
      /**
       * 显示菜单
       * @return {[type]} [description]
       */
      menuModalEvent () {
        this.showMenuModal = true
      },
      /**
       * 删除设备
       * @return {[type]} [description]
       */
      deleteDevice () {
        this.showDeleteModal = false
        this.showLoading('正在删除设备..')
        setTimeout(() => {
          this.hideLoading()
          this.showMessage('删除超时！')
        }, 3000)
      },
      /**
       * 设备初始化
       * @param  {[type]} devices [description]
       * @return {[type]}         [description]
       */
      deviceInit (devices) {
        devices = devices || []
        var self = this
        if (devices.length <= 0) {
          return
        }

        var device = null
        for (var i = 0; i < devices.length; i++) {
          if (parseInt(devices[i].id) === parseInt(this.deviceId)) {
            device = devices[i]
          }
        }

        if (device) {
          this.device.connect = device
          this.device.online = device.online
          device.on('data', function (data) {
            self.dataProcess(data.data.datapoint, device)
            // if (device.datapoint) {
            //   device.datapoint[device.id] = data.data.datapoint
            // } else {
            //   device.datapoint = new Array[7]
            //   self.resetThis().curDevice[self.device.id] = data.data.datapoint
            // }
          })
          device.on('statuschange', function (status) { // status=1 表示设备在线，status=0表示设备离线 status=其他 发生错误
            self.log('设备状态改变为' + status)
            self.device.online = status
          })

          if (!device.datapoint) {
            device.datapoint = {}
          }

          if (device.datapoint[device.id]) {
            var list = device.datapoint[device.id]
            this.saveDataProcess(list)
          } else {
            device.datapoint[device.id] = new Array(7)
          }
        }
      },

      saveDataProcess (list) {
        for (var i = 0; i < list.length; i++) {
          switch (i) {
            case 0: // 烟雾
              this.device.smoke = Boolean(list[i])
              break
            case 1: // 温度
              this.device.temperature = Number(list[i])
              break
            case 2: // 有毒气体
              this.device.gas = Number(list[i])
              break
            // 不存储温度和有毒气体设置数据。一下2个数据端点用来发送数据
            case 3: // 温度设置
              this.alert.temperature = Number(list[i])
              break
            case 4: // 有毒气体设置
              this.alert.gas = Number(list[i])
              break
            /* 报警信息不做处理, app已知设备告警阈值，只根据设备状态数值判断 */
            case 5: // 温度报警
              console.log('收到温度报警')
              break
            case 6: // 有毒气体报警
              console.log('收到有毒气体报警')
              break
            default:
              break
          }
        }
      },

      // 返回值表示是否触发告警
      dataProcess (list, device) {
        console.log(list)
        list.forEach((item) => {
          if (!device) {
            return
          }
          if (!device.datapoint) {
            device.datapoint = {}
          }
          if (device.datapoint[device.id]) {
            device.datapoint[device.id][item.index] = item.value
          } else {
            device.datapoint[device.id] = new Array(7)
            device.datapoint[device.id][item.index] = item.value
          }
          switch (item.index) {
            case 0: // 烟雾
              this.device.smoke = item.value
              break
            case 1: // 温度
              this.device.temperature = item.value
              break
            case 2: // 有毒气体
              this.device.gas = item.value
              break
            // 不存储温度和有毒气体设置数据。一下2个数据端点用来发送数据
            case 3: // 温度设置
              // console.log('温度设置')
              // if (device) {
              //   var data = '340'
              //   var data64 = base64.encode(JSON.stringify(data))
              //   console.log(data64)
              //   device.emit('senddata', {
              //     data: data64,
              //     type: 'datapoint'
              //   }, function (res) {
              //     console.log(res)
              //   })
              // }
              //
              this.alert.temperature = item.value
              break
            case 4: // 有毒气体设置
              this.alert.gas = item.value
              break
            /* 报警信息不做处理, app已知设备告警阈值，只根据设备状态数值判断 */
            case 5: // 温度报警
              console.log('收到温度报警')
              break
            case 6: // 有毒气体报警
              console.log('收到有毒气体报警')
              break
            default:
              break
          }
        })
      }
    }
  }
</script>

<style lang="stylus">
  @import '../../../shared/assets/style/common'

  .device-details
    background-size 100%
    font-weight bold
    .warn-mask
      width 100%
      height 100%
      position absolute
      top 0
      left 0
      background-color rgba(0,0,0,0.3)
    .menu-btn-box
      color #b55318
      height 0.82rem
      position absolute
      right 0.5rem
      top 0.8rem
      /*background #1d1d1d*/
      background linear-gradient(top, #ffedb6, #ffdb6f, #ffc617)

      padding 0 0.3rem
      border-radius 0.2rem
      box-sizing border-box
      box-shadow 0 0.05rem 0.12rem 0.03rem rgba(0,0,0,0.3)
      .menu-icon-box
      .text
        height 100%
        overflow hidden
        float left
        line-height 0.8rem
        display inline-block
      .menu-icon-box
        margin-top 0.11rem
        margin-right 0.12rem
    .modal-box
      color #fff
      /*min-width 2rem*/
      height auto
      box-shadow 0 0.05rem 0.12rem 0.03rem rgba(0,0,0,0.3)
      background linear-gradient(top, #ffedb6, #ffdb6f, #ffc617)
      /*background #1d1d1d*/
      border-radius 0.2rem
      padding 0 0.6rem
      box-sizing border-box
      position absolute
      right 0.5rem
      top 2rem
      .li
        font-size 0.5rem
        line-height 1.5rem
        border-bottom 0.02rem solid #b55318
        padding 0 0.05rem
        color #b55318
        text-align center
        position relative
        &:last-child
          border-bottom 0
        .select
          position absolute
          top 0
          left 0
          width 100%
          height 100%
          opacity 0
    .device-state-box
      width 100%
      padding-top 2.7rem
      box-sizing border-box
      text-align center
      .warn-box
        width 100%
        position relative
        font-size 0
        height 4rem
        .warn
          width 33.3%
          height 100%
          display inline-block
          overflow hidden
          font-size 0.43rem
          text-align center
          position relative
          opacity 0.6
          &.visible
            opacity 1

          .icon-box
            width 2.8rem
            height 2.8rem
            margin 0.2rem auto 0
            position relative
            /*border-radius 50%*/
            /*box-shadow 0 0 0 0.2rem rgba(0,0,0,0.15)*/
            background-size auto 2.8rem
            background-position center
            background-repeat no-repeat
            i
              display block
              width 1.2rem
              height 1.2rem
              background-size 100% 100%
              margin 0.8
              position absolute
              top 50%
              left 50%
              transform translate3d(-50%, -50%, 0)
              opacity 0.5
          .text
            padding 0.15rem
            font-size 0.45rem
            text-shadow 0 0.08rem 0.15rem rgba(0,0,0,0.8)
            font-weight bold
        .smoke-box
          .warn-state
            box-shadow 0 0 0 0.2rem rgba(178, 117, 58,0.15)
            background-color rgb(178, 117, 58)

        .fire-box
          .warn-state
            box-shadow 0 0 0 0.2rem rgba(255, 68, 49,0.15)
            background-color: rgb(255, 68, 49)
        .gas-box
          .warn-state
            box-shadow 0 0 0 0.2rem rgba(93, 123, 46,0.15)
            background-color: rgb(93, 123, 46)
      .this-state
        display inline-block
        width auto
        max-width 90%
        line-height 0.5rem
        color #fff
        /*background-color rgb(102,203,58)*/
        margin 0.4rem auto
        text-align center
        font-size 0.6rem
        /*padding 0 1rem*/
        &.normal
          margin-top 1.5rem
        .icon-box
          margin 0 auto
          width 4rem
          height 4rem
          background-size 100%
          background-position center
        span
          text-shadow 0 0.05rem 0.15rem rgba(0,0,0,.3)
    .device-info
      height 3.4rem
      width 100%
      position absolute
      bottom 0
      left 0
      /*background rgba(0,0,0,0.4)*/
      .container
        width 100%
        height 100%
        padding 0.6rem 0.3rem
        box-sizing border-box
        font-size 0
        .info
          width 3.1rem
          height 100%
          overflow hidden
          display inline-block
          font-size 0.4rem
          text-align center
          border-right 1px solid #fff
          &:last-child
            border-right 0
          .title
            height 1rem
            line-height 1rem
            font-size 0.5rem
            color #fff
            text-shadow 0 0 0.15rem rgba(255,0,0,1)
          .msg
            font-size 0.6rem
            color #ea181e


    .modal
      .modal-body
        p
          padding-bottom 0.1rem
          color #946244
        .rename-box
          width 100%
          padding 0 10%
          box-sizing border-box
          position relative
          .input-box
            width 100%
            height 1rem
            line-height 1rem
            background #fff
            border-radius 0.2rem
            padding 0 1rem 0 0.5rem
            box-sizing border-box
            border 0.05rem solid #b55318
          .rename-input
            display inline-block
            width 100%
            height 0.6rem
            font-size 0.4rem
            color #333
            border 0
            background none
          .clear-btn
            width 1rem
            height 1rem
            position absolute
            right 0.8rem
            top 0
            background-size 0.5rem 0.5rem
            background-position center center
            background-repeat no-repeat

      .btn-group
        clearfix()
        width 80%
        box-sizing border-box
        margin 0 auto
       .btn-box
        border-top 0
        height 2.6rem
        width 50%
        float left
        line-height 2.6rem
        text-align center
        padding 0 0.4rem
        box-sizing border-box
        .btn
          width 100%
          height 1rem
          background-color #b55318
          /*border-right 0.03rem solid #b55318*/
          font-size 0.45rem


</style>
